package cc.admin.common.db.util;

import cc.admin.common.sys.vo.LoginUser;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
/**
 * @author: ZhangHouYing
 * @date: 2023-09-28 9:17
 */
@Slf4j
public class TenantUtil {

	public static final String fromTenant = "a01";

	/**
	 * 替换租户编号
	 *
	 * @param str
	 * @return
	 */
	public static String replaceTenantTableName(String str) {
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		if (user != null) {
			log.info("----进入表名替换：{}", str);
			str = replaceTenantTableName(str, user.getTenantId());
			log.info("----替换后：{}", str);
		}
		return str;
	}

	/**
	 * 替换租户编号
	 *
	 * @param str
	 * @param toTenantId
	 * @return
	 */
	public static String replaceTenantTableName(String str, String toTenantId) {
		if (StrUtil.isEmpty(str)) {
			return str;
		}
		return str.replaceAll(appendUnderline(fromTenant), appendUnderline(toTenantId));
	}

	/**
	 * 替换租户编号
	 *
	 * @param str
	 * @param fromTenantId
	 * @param toTenantId
	 * @return
	 */
	public static String replaceTenantTableName(String str, String fromTenantId, String toTenantId) {
		if (StrUtil.isEmpty(str)) {
			return str;
		}
		return str.replaceAll(appendUnderline(fromTenantId), appendUnderline(toTenantId));
	}

	/**
	 * 末尾拼接下划线
	 *
	 * @param str
	 * @return
	 */
	public static String appendUnderline(String str) {
		return String.format("%s_", str);
	}
}
